package org.jeecg.modules.quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.moenydata.uitils.TimeUtil;
import org.jeecg.modules.demo.pointcount.entity.PointCount;
import org.jeecg.modules.demo.pointcount.redis.consumer.SendAndStorageProcess;
import org.jeecg.modules.demo.pointcount.redis.util.Config;
import org.jeecg.modules.demo.pointcount.service.IPonintCountService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yw
 * @Date 2021/3/6 9:38
 * 打点统计（05,15,25,35,45,55）每小时执行
 *
 */
@Slf4j
public class RedisTheardPointCountJob implements Job {


    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */

    @Autowired
    private IPonintCountService iPonintCountService;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        /** old start */
//        log.info(String.format(" 插入每日数据 !  时间:" + DateUtils.getTimestamp()));
//        //sendAndStorageProcess.getMsgCheckdata(parameter);
//        PointCount p=new PointCount();
//        p.setTableName("hc_cq_pointcount");
//        p.setCtime(TimeUtil.getNowTimestamp());
//        //iPonintCountService.addPointCount(p);
        /** old end */

        /** zrikka start */
        // 每3分钟执行一次
        long start = System.currentTimeMillis();// 起始
        pointStatistics(Config.POINT_ADD_EVENT);
        long end = System.currentTimeMillis();// 结束
        StringBuffer str = new StringBuffer();
        str.append("记录打点统计,当次用时: ");
        str.append(end - start);
        str.append("ms");
        log.info(String.format(str.toString()));
        /** zrikka end */
    }

    /** zrikka start */
    /** zrikka 打点统计 每3分钟执行一次 */
    public void pointStatistics(String key){
        Map<Object, Object> map = redisUtil.hgetAll(key);
        Map<String,PointCount> res = new HashMap<String,PointCount>();
        // 获取所有key
        for (Object mapSet : map.keySet()) {
            String keys = (String)mapSet;// 键  2021-03-19&hc_cq_eventdata&ks&301&0
            Object valSet = map.get(keys);
            Integer vals = (Integer)valSet;// 值  打点数量
            // 解析数据
            String[] keysArr = keys.split("&");
            String time = keysArr[0];// 时间
            String tablename = keysArr[1];// 表名
            String channl = keysArr[2];// 渠道
            String event = keysArr[3];// 事件
            String type = keysArr[4];// 类型(1今日新用户 0全部用户)
            // 构造键
            StringBuffer str = new StringBuffer();
            str.append(time);
            str.append("&");
            str.append(tablename);
            str.append("&");
            str.append(channl);
            str.append("&");
            str.append(type);
            PointCount pointCo = res.get(str.toString());
            if(pointCo == null){
                pointCo = new PointCount();
            }
            pointCo.settingNum(Integer.valueOf(event),String.valueOf(vals));
            res.put(str.toString(),pointCo);
        }
        // 更新打点统计
        for (Object result : res.keySet()) {
            String keys = (String)result;// 键  2021-03-19&hc_cq_eventdata&ks&0
            Object valSet = res.get(keys);
            PointCount req = (PointCount)valSet;// 值  所有打点数量

            String[] keysArr = keys.split("&");
            req.setCtime(keysArr[0]);// 日期
            req.setDataName(keysArr[1]);// 表名
            req.setChannel(keysArr[2]);// 渠道
            req.setType(keysArr[3]);// 打点数据标识

            String exist = iPonintCountService.queryRecordIsExist(req);
            if(exist == null || "".equals(exist)){
                // 新增
                iPonintCountService.addPointCountRecord(req);
            }
            if("1".equals(req.getType())){
                // 获取今日注册用户总数
                Integer regNum = (Integer)redisUtil.hget(Config.POINT_TODAY_USER_NUM, req.getCtime());
                if(regNum != null){
                    req.setRegUserNum(String.valueOf(regNum));// 注册用户总数
                }
            }
            // 修改数量
            iPonintCountService.updatePointCount(req);
        }
    }
    /** zrikka end */
}
